package com.fanghuaiming.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/****
 * @description:
 * @version:1.0.0
 * @author fanghuaiming
 * @data Created in 2020/11/24 下午2:46
 *
 */
@Slf4j
@Service
public class SentinelService {

    /**
     * @Description: 正常加载Sentinel
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/24 下午2:47
     * @version:1.0.0
     */
    @SentinelResource(value = "loadSentinel" ,blockHandler = "blockHandler",fallback = "fallBack")
    public String loadSentinel(String name){
        if(name.equals("a")){
            throw new ExceptionInInitializerError("业务异常,参数不能是: " + name);
        }
        return "load Sentinel";
    }

    /**
     * @Description: 控制流量接口
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/24 下午3:02
     * @version:1.0.0
     */
    public String blockHandler(String name , BlockException be){
        return "限制Sentinel";
    }

    /**
     * @Description: 异常流控
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/24 下午3:04
     * @version:1.0.0
     */
    public String fallBack(String name ,Throwable e){
        log.error("业务方法中出现异常:{}",e.getMessage());
        return "业务方法中出现异常: " + name + " -> " + e.getMessage();
    }

    /**
     * @Description: Warm up
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/24 下午3:10
     * @version:1.0.0
     */
    public String warmUp() {

        return "Sentinel Warm Up";
    }

    /**
     * @Description: blockQueue排队等待，类似RateLimiter限流（提前消费即透支）
     *
     * @param:
     * @return:
     * @auther: fanghuaiming
     * @date: 2020/11/24 下午3:15
     * @version:1.0.0
     */
    public String blockQueue() {
        return "Sentinel blockQueue";
    }
}
